package com.property.demo.config;

import com.property.demo.dto.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.persistence.EntityNotFoundException;
import java.nio.BufferOverflowException;
import java.util.Arrays;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 处理IndexOutOfBoundsException
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public ResponseEntity<ApiResponse> handleIndexOutOfBoundsException(IndexOutOfBoundsException ex, WebRequest request) {
        logger.error("发生索引越界异常: {}", ex.getMessage(), ex);
        
        // 详细记录异常信息
        logger.error("异常堆栈跟踪: {}", Arrays.toString(ex.getStackTrace()));
        logger.error("请求详情: {}", request.getDescription(true));
        
        ApiResponse apiResponse = new ApiResponse(false, "处理请求时发生索引越界错误，请联系系统管理员");
        return new ResponseEntity<>(apiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理BufferOverflowException
    @ExceptionHandler(BufferOverflowException.class)
    public ResponseEntity<ApiResponse> handleBufferOverflowException(BufferOverflowException ex, WebRequest request) {
        logger.error("发生缓冲区溢出异常: {}", ex.getMessage(), ex);
        
        ApiResponse apiResponse = new ApiResponse(false, "处理请求时发生缓冲区溢出错误，请尝试减小请求数据大小");
        return new ResponseEntity<>(apiResponse, HttpStatus.BAD_REQUEST);
    }

    // 处理EntityNotFoundException
    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity<ApiResponse> handleEntityNotFoundException(EntityNotFoundException ex, WebRequest request) {
        logger.error("实体未找到异常: {}", ex.getMessage(), ex);
        
        ApiResponse apiResponse = new ApiResponse(false, ex.getMessage());
        return new ResponseEntity<>(apiResponse, HttpStatus.NOT_FOUND);
    }

    // 处理所有其他未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse> handleAllExceptions(Exception ex, WebRequest request) {
        logger.error("发生未处理的异常: {}", ex.getMessage(), ex);
        logger.error("异常类型: {}", ex.getClass().getName());
        logger.error("异常堆栈跟踪: {}", Arrays.toString(ex.getStackTrace()));
        logger.error("请求详情: {}", request.getDescription(true));
        
        ApiResponse apiResponse = new ApiResponse(false, "处理请求时发生错误，请联系系统管理员");
        return new ResponseEntity<>(apiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
} 
